﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using QuanCafe.DataLayer;
using QuanCafe.BusinessLayer;
using System.IO;
namespace QuanCafe.Admin
{
    public partial class News : System.Web.UI.Page
    {
        #region Declare
        SQLHelper db = new SQLHelper();
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            this.edtContent.BasePath = this.Page.ResolveUrl("~/FCKEditor/");
            this.edtContent.SkinPath = this.Page.ResolveUrl("~/FCKEditor/editor/skins/office2003/");

            if (!IsPostBack)
            {
                this.fnLoadData();
            }
        }
        protected void btnViewAll_Click(object sender, EventArgs e)
        {
            fnLoadData();
        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            int quantity = Convert.ToInt32(txtViewQuantity.Text);
            dtgNew.PageSize = quantity;
            this.fnLoadData();
        }

        //Load Data
        public void fnLoadData()
        {
            try
            {
                QuanCafe.BusinessLayer.News New = new QuanCafe.BusinessLayer.News();
                DataTable dtb = New.GetAll();
                dtgNew.DataSource = dtb;
                dtgNew.DataBind();
                for (int i = 0; i < dtgNew.Items.Count; i++)
                {
                    if (dtb.Rows[i]["Status"].ToString() == "1")
                    {
                        ((ImageButton)dtgNew.Items[i].FindControl("btnActive")).ImageUrl = "~/Images/icons/btnOK.jpg";

                    }
                    else
                    {
                        ((ImageButton)dtgNew.Items[i].FindControl("btnActive")).ImageUrl = "~/Images/icons/btnKO.jpg";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }

        }
        public void fnClearControl()
        {
            chk.Checked = false;
            txtTags.Text = "";
            txtNewID.Text = "";
            txtTitle.Text = "";
            txtDescription.Text = "";
            edtContent.Value = "";
            txtImageName.Text = "";
            imgBox.ImageUrl = "~/images/icons/NoImage.JPG";
            lblError.Text = "";
            btnChangePicture.Visible = false;
            txtFileImageUpLoad.Visible = true;
        }
        public void fnLoadDataByID(int IntID)
        {
            try
            {
                QuanCafe.BusinessLayer.News New = new QuanCafe.BusinessLayer.News();
                New.NewsID = IntID;
                DataRow dr = New.GetByID();
                txtNewID.Text = IntID.ToString();

                txtTitle.Text = dr["Title"].ToString();
                txtTags.Text = dr["Tags"].ToString();
                txtDescription.Text = dr["Description"].ToString();
                edtContent.Value = dr["Content"].ToString();

                if (dr["ThumbnailURL"].ToString() != "" || dr["ThumbnailURL"] != null)
                {
                    imgBox.ImageUrl = Page.ResolveUrl(dr["ThumbnailURL"].ToString());
                    txtFileImageUpLoad.Visible = false;
                    txtImageName.Text = dr["ThumbnailURL"].ToString();
                    btnChangePicture.Visible = true;
                }
                else
                {
                    imgBox.ImageUrl = "~/images/icons/NoImage.JPG";
                    txtFileImageUpLoad.Visible = true;
                    btnChangePicture.Visible = false;
                }

                if (dr["SpecialNews"].ToString().Trim().ToLower() == "1"
                        || dr["SpecialNews"].ToString().Trim().ToLower() == "true") chk.Checked = true;

                else chk.Checked = false;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        private void fnChangeActive(int ID)
        {
            QuanCafe.BusinessLayer.News newsObj = new QuanCafe.BusinessLayer.News();
            newsObj.NewsID = ID;
            newsObj.ChangeActive();
            fnLoadData();
        }

        private void fnChangeRank(int ID, string cmd)
        {
            QuanCafe.BusinessLayer.News newsObj = new QuanCafe.BusinessLayer.News();
            newsObj.NewsID = ID;
            newsObj.ChangeRank(cmd);
            fnLoadData();
        }

        protected void dtgNew_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            int Id = -1;
            string nName = e.CommandName.ToLower();
            switch (nName)
            {
                case "edit":
                    Id = Convert.ToInt32(dtgNew.Items[e.Item.ItemIndex].Cells[0].Text);
                    fnLoadDataByID(Id);
                    break;
                case "activechange":
                    Id = Convert.ToInt32(dtgNew.Items[e.Item.ItemIndex].Cells[0].Text);
                    fnChangeActive(Id);
                    break;
                case "up":
                    Id = Convert.ToInt32(dtgNew.Items[e.Item.ItemIndex].Cells[0].Text);
                    fnChangeRank(Id, "up");
                    break;
                case "down":
                    Id = Convert.ToInt32(dtgNew.Items[e.Item.ItemIndex].Cells[0].Text);
                    fnChangeRank(Id, "down");
                    break;
            }
        }

        protected void dtgNew_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            dtgNew.CurrentPageIndex = e.NewPageIndex;
            this.fnLoadData();

        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            this.fnClearControl();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string strImageURL = "";
                string strFileName = "";

                QuanCafe.BusinessLayer.News newsObj = new QuanCafe.BusinessLayer.News();
                if (txtNewID.Text == "") // Insert
                {
                    //Upload hinh 
                    if (txtFileImageUpLoad.FileName != "")
                    {
                        string a = txtFileImageUpLoad.FileName;
                        //---------------------------------
                        string mext = "";
                        mext = a.Substring(a.LastIndexOf("."));
                        if (mext != ".png" && mext != ".gif" && mext != ".jpeg" && mext != ".jpg" && mext != ".bmp" && mext != ".GIF" && mext != ".JPEG" && mext != ".JPG" && mext != ".BMP")
                        {
                            this.lblError.Text = "Tập tin upload không phải tập tin dạng hình.";
                            return;
                        }
                        // Kiem tra Dung luong hinh nho Hon 200kb
                        int intMaxImageSize = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxUploadImageSize"].Trim()) * 1024;
                        int filesize = txtFileImageUpLoad.PostedFile.ContentLength;
                        if (filesize > intMaxImageSize)
                        {
                            lblError.Text = "Dung lượng tập tin Upload đã vượt quá quy định cho phép(" + intMaxImageSize.ToString() + "kb).";
                            return;
                        }
                        //End Kiem tra Dung luong hinh nho Hon 200kb
                        strFileName = CLSCommon.UploadImage(txtFileImageUpLoad, "NewsImages", "NewsImage", this);
                        strImageURL = "~" + ConfigurationManager.AppSettings["NewsImages"].ToString() + strFileName;
                    }

                    //Save Thong tin San pham 
                    newsObj.activity = "Insert";
                    newsObj.ThumbnailURL = strImageURL;
                    newsObj.Title = txtTitle.Text.Trim();
                    newsObj.Tags = txtTags.Text.Trim();
                    newsObj.Description = txtDescription.Text.Trim();
                    newsObj.Content = edtContent.Value.Trim();
                    newsObj.Creator = Session["AdminName"].ToString();
                    int isChecked = 0;
                    if (chk.Checked == true) isChecked = 1;
                    else isChecked = 0;
                    newsObj.isSpecialNews = isChecked;
                    newsObj.InsertUpdate();
                    lblError.Text = "Dữ liệu thêm mới thành công";
                }
                else // Update
                {
                    if (btnChangePicture.Visible == false && txtFileImageUpLoad.FileName != "")
                    {
                        //Xoa hinh da update tu truoc
                        CLSCommon.DeleteImage(txtImageName.Text, ConfigurationManager.AppSettings["NewsImages"].ToString(), this);
                        //CLSCommon.DeleteImage(txtImageName.Text.Substring(0, txtImageName.Text.LastIndexOf(".")) + "_Thumb" + txtImageName.Text.Substring(txtImageName.Text.LastIndexOf(".")), ConfigurationManager.AppSettings["ProductImages"].ToString(), this);
                        if (txtFileImageUpLoad.FileName != "")
                        {
                            string a = txtFileImageUpLoad.FileName;
                            //---------------------------------
                            string mext = "";
                            mext = a.Substring(a.LastIndexOf("."));
                            if (mext != ".png" && mext != ".gif" && mext != ".jpeg" && mext != ".jpg" && mext != ".bmp" && mext != ".GIF" && mext != ".JPEG" && mext != ".JPG" && mext != ".BMP")
                            {
                                this.lblError.Text = "Tập tin upload không phải tập tin dạng hình.";
                                return;
                            }
                            // Kiem tra Dung luong hinh nho Hon 200kb
                            int intMaxImageSize = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxUploadImageSize"].Trim()) * 1024;
                            int filesize = txtFileImageUpLoad.PostedFile.ContentLength;
                            if (filesize > intMaxImageSize)
                            {
                                lblError.Text = "Dung lượng tập tin Upload đã vượt quá quy định cho phép(200kb).";
                                return;
                            }
                            //End Kiem tra Dung luong hinh nho Hon 200kb
                            strFileName = CLSCommon.UploadImage(txtFileImageUpLoad, "NewsImages", "NewsImage", this);
                            strImageURL = "~" + ConfigurationManager.AppSettings["NewsImages"].ToString() + strFileName;

                        }
                    }
                    //Save Thong tin San pham 
                    newsObj.activity = "Update";
                    newsObj.NewsID = Convert.ToInt32(txtNewID.Text);
                    newsObj.ThumbnailURL = strImageURL;
                    newsObj.Title = txtTitle.Text.Trim();
                    newsObj.Tags = txtTags.Text.Trim();
                    newsObj.Description = txtDescription.Text.Trim();
                    newsObj.Content = edtContent.Value.Trim();
                    newsObj.Creator = Session["AdminName"].ToString();
                    int isChecked = 0;
                    if (chk.Checked == true) isChecked = 1;
                    else isChecked = 0;
                    newsObj.isSpecialNews = isChecked;
                    newsObj.InsertUpdate();
                    lblError.Text = "Dữ liệu cập nhật thành công";
                }

                fnLoadData();
                fnClearControl();

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                string strID = "";
                for (int i = 0; i < dtgNew.Items.Count; i++)
                {
                    if (((CheckBox)dtgNew.Items[i].FindControl("chkSelect")).Checked == true)
                    {
                        strID += dtgNew.Items[i].Cells[0].Text.Trim() + "$";//Cot dau tien phai de cai ID 
                        if (Directory.Exists(Server.MapPath("~" + ConfigurationManager.AppSettings["NewsImages"].ToString() + dtgNew.Items[i].Cells[0].Text.Trim())))
                        {
                            System.IO.Directory.Delete(Server.MapPath("~" + ConfigurationManager.AppSettings["NewsImages"].ToString() + dtgNew.Items[i].Cells[0].Text.Trim()), true);
                        }
                    }
                }
                CLSCommon.DeleteListRecordImage("SP_News", strID, "ThumbnailURL", "NewsID", "Images", this);
                fnLoadData();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        protected void btnChangePicture_Click(object sender, EventArgs e)
        {
            try
            {
                txtFileImageUpLoad.Visible = true;
                imgBox.ImageUrl = Page.ResolveUrl("~/images/icons/NoImage.JPG");
                btnChangePicture.Visible = false;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }
    }
}
